const app = getApp()
const ajax = require('../../utils/ajax')
Page({
  data: {
    carts: [], //数据
    iscart: false,
    hidden: false,
    isAllSelect: false,
    totalMoney: 0,
    isRegister: false,
    vip_id: '',
    mobile: '',
    customerid: '',
    pic_domain: '',
    can_getuserinfos: '',
    can_getuserinfo: wx.getStorage({
      key: '',
      success: function(res) {}
    }),
    RESERVE_MONEY:68,
  
// 购物提醒
    buyTip:""
  },

  shopping() {
    wx.switchTab({
      url: '/pages/buyGuide/buyGuide'
    })
  },

  getGoodsList(type) {
    ajax.wxRequest({
      url: '/index.php/Api/SApi/index/m/getGoodsList',
      data: {
        type_id: type,
        is_select: 1,
        btype: 1,
        is_old: 1
      }
    }).then(res => {
      res.datas && this.setData({
        tablist: res.selected_type,
        goodsList: this.data.goodsList.concat(res.datas)
      })
      if (this.data.firstRequest) {
        this.setData({
          bechoice: res.selected_type[0]['id'],
          firstRequest: false
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    let that = this
    // 获取产品
    let order_share
    if (options !== undefined) {
      order_share = options.order_share_id || 0
    }
    if (order_share > 0) {
      wx.request({
        url:
          app.urlData.getURL +
          '/index.php/api/SApi/index/key/' +
          app.urlData.key +
          '/m/updateLeadingShareId/wid/' +
          app.urlData.wid +
          '/sign/' +
          wx.getStorageSync('sign'),
        method: 'post',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
          leading_user_id: order_share,
          page_src: 'pages/shopCart/shopCart?order_share_id=' + order_share
        },
        success: res => {}
      })
    }

    //检查是否授权，如未授权，将自动跳转至授权页面
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.setStorage({
            key: 'can_getuserinfo',
            data: 1
          })
          that.setData({
            can_getuserinfos: 1
          })
        } else {
          wx.setStorage({
            key: 'can_getuserinfo',
            data: 0
          })
          that.setData({
            can_getuserinfos: 0
          })
          return false
        }
      }
    })
  },
  onShow: function() {
    let that = this
    // 获取产品
    wx.request({
      url: app.urlData.getURL + '/index.php/api/SApi/index/m/cartIndex',
      data: {
        key: app.urlData.key,
        wid: app.urlData.wid,
        sign: wx.getStorageSync('sign')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
       
        if (res.data.status == 1) {
          that.data.totalMoney = 0
          let len = 0
          // 计算价格
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].selected == 1) {
              len++
              if (wx.getStorageSync('is_vip') == 1) {
                that.data.totalMoney =
                  that.data.totalMoney +
                  res.data.data[i].price_discounts * res.data.data[i].goods_num
              } else {
                that.data.totalMoney =
                  that.data.totalMoney +
                  res.data.data[i].price * res.data.data[i].goods_num
              }
              res.data.data[i].selected = 1
            } else {
              res.data.data[i].selected = 0
            }
          }
          // 如果全部选中则全选按钮开启
          if (len == res.data.data.length) {
            that.setData({
              isAllSelect: true
            })
          }
          that.setData({
            RESERVE_MONEY: res.data.RESERVE_MONEY,
            carts: res.data.data,
            buyTip: res.data.order_tip.desc,
            totalMoney: that.data.totalMoney,
            hidden: true,
            iscart: false,
            pic_domain: res.data.pic_domain
          })
        } else {
          that.setData({
            iscart: true,
            hidden: false
          })
        }
      }
    })
    that.notRegister()
    that.onLoad()
  },
  getUserInfo88: function(e) {
    let that = this
    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
      wx.showToast({
        title: '授权才能参与购买和享受超值优惠活动哦！',
        icon: 'none',
        duration: 3000
      })
    } else if (e.detail.errMsg == 'getUserInfo:ok') {
      app.getUserInfo(
        wx.getStorageSync('sign'),
        e.detail.userInfo.nickName,
        e.detail.userInfo.avatarUrl,
        e.detail.userInfo.gender,
        e.detail.encryptedData,
        e.detail.iv
      )

      that.setData({
        can_getuserinfos: 1
      })
      wx.setStorage({
        key: 'can_getuserinfo',
        data: 1
      })
    }
  },
  notRegister: function() {
    let that = this
    wx.request({
      url:
        app.urlData.getURL +
        '/index.php/api/SApi/index/key/' +
        app.urlData.key +
        '/m/is_customerid/wid/' +
        app.urlData.wid +
        '/sign/' + wx.getStorageSync('sign'),
      method: 'GET',
      success: res => {
        let isRegister = false
        console.log('更替为执行完', res)
        if (res.data.status == 1) {
          isRegister = true
        }
        that.setData({
          vip_id: res.data.vip_id,
          mobile: res.data.mobile,
          customerid: res.data.customerid,
          isRegister: isRegister
        })
        if (res.data.vip_id != 0 && res.data.vip_id != '') {
          wx.setStorageSync('vip_id', res.data.vip_id)
        }
      }
    })
  },

  //勾选事件处理函数
  switchSelect: function(e) {
    let that = this
    // 获取item项的id，和数组的下标值
    let Allprice = 0
    let id = e.target.dataset.id
    let index = parseInt(e.target.dataset.index)
    that.data.carts[index].selected = !that.data.carts[index].selected
    //价钱统计
    if (that.data.carts[index].selected) {
      if (wx.getStorageSync('is_vip') == 1) {
        that.data.totalMoney =
          that.data.totalMoney +
          that.data.carts[index].price_discounts *
            that.data.carts[index].goods_num
      } else {
        that.data.totalMoney =
          that.data.totalMoney +
          that.data.carts[index].price * that.data.carts[index].goods_num
      }
      that.clickStatus(that.data.carts[index].id, 1)
    } else {
      if (wx.getStorageSync('is_vip') == 1) {
        that.data.totalMoney =
          that.data.totalMoney -
          that.data.carts[index].price_discounts *
            that.data.carts[index].goods_num
      } else {
        that.data.totalMoney =
          that.data.totalMoney -
          that.data.carts[index].price * that.data.carts[index].goods_num
      }
      that.clickStatus(that.data.carts[index].id, 0)
    }
    //是否全选判断
    for (let i = 0; i < that.data.carts.length; i++) {
      if (wx.getStorageSync('is_vip') == 1) {
        Allprice =
          Allprice +
          that.data.carts[i].price_discounts * that.data.carts[i].goods_num
      } else {
        Allprice =
          Allprice + that.data.carts[i].price * that.data.carts[i].goods_num
      }
    }
    if (Allprice == that.data.totalMoney) {
      that.data.isAllSelect = true
    } else {
      that.data.isAllSelect = false
    }
    that.setData({
      carts: that.data.carts,
      totalMoney: that.data.totalMoney,
      isAllSelect: that.data.isAllSelect
    })
  },
  //全选
  allSelect: function(e) {
    //处理全选逻辑
    let that = this
    let cart_id = []
    if (!that.data.isAllSelect) {
      that.data.totalMoney = 0
      for (let i = 0; i < that.data.carts.length; i++) {
        that.data.carts[i].selected = 1
        if (wx.getStorageSync('is_vip') == 1) {
          that.data.totalMoney =
            that.data.totalMoney +
            that.data.carts[i].price_discounts * that.data.carts[i].goods_num
        } else {
          that.data.totalMoney =
            that.data.totalMoney +
            that.data.carts[i].price * that.data.carts[i].goods_num
        }
        cart_id.push(that.data.carts[i].id)
      }
      // 多个商品id以逗号分隔
      let id = cart_id.join(',')
      that.clickStatus(id, 1)
    } else {
      for (let i = 0; i < that.data.carts.length; i++) {
        that.data.carts[i].selected = 0
        cart_id.push(that.data.carts[i].id)
      }
      that.data.totalMoney = 0
      // 多个商品id以逗号分隔
      let id = cart_id.join(',')
      that.clickStatus(id, 0)
    }
    that.setData({
      carts: that.data.carts,
      isAllSelect: !that.data.isAllSelect,
      totalMoney: that.data.totalMoney
    })
  },
  // 选中状态
  clickStatus(cart_ids, status) {
    wx.request({
      url:
        app.urlData.getURL +
        '/index.php/api/SApi/index/key/' +
        app.urlData.key +
        '/m/updateCartStatus/wid/' +
        app.urlData.wid +
        '/sign/' +
        wx.getStorageSync('sign') +
        '/cart_ids/' +
        cart_ids +
        '/status/' +
        status,
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        let that = this
        console.log('选中状态', res)
      }
    })
  },
  // 去结算
  toBuy(e) {
    let that = this
    if (that.data.isRegister == false) {
      let pagePath = '../tryoutInfo/tryoutInfo'
      wx.showModal({
        title: '提示',
        content: '您还没有注册，是否去注册',
        success: function(res) {
          console.log('注册地址', that.data.vip_id)
          if (res.confirm) {
            wx.switchTab({
              //注册地址
              url:
                '/pages/user/user?pagePath=' +
                pagePath +
                '&vip_id=' +
                that.data.vip_id
            })
          }
        }
      })
    } else {
      let skip_List = that.data.carts
      for (let i = 0; i < skip_List.length; i++) {
        if (skip_List[i].selected == 1) {
          // wx.showModal({
          //   title: '提示',
          //   content: that.data.buyTip,
          //   success(res) {
          //     if (res.confirm) {
                wx.navigateTo({
                  url: '../settlement/settlement?payType=' + e.currentTarget.dataset.type
                })
          //     } else if (res.cancel) {
          //       console.log('用户点击取消')
          //     }
          //   }
          // })
          return
        }
      }
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 2000
      })
    }
  },
  //数量变化处理
  handleQuantityChange(e) {
    var componentId = e.componentId
    var quantity = e.quantity
    this.data.carts[componentId].count.quantity = quantity
    this.setData({
      carts: this.data.carts
    })
  },
  /* 减数 */
  delCount: function(e) {
    let that = this
    let index = e.target.dataset.index
    let count = that.data.carts[index].goods_num
    let cart_id = that.data.carts[index].id
    wx.request({
      url:
        app.urlData.getURL +
        '/index.php/api/SApi/index/key/' +
        app.urlData.key +
        '/m/updateCartCount/wid/' +
        app.urlData.wid +
        '/sign/' +
        wx.getStorageSync('sign') +
        '/cart_id/' +
        cart_id +
        '/op/' +
        'removeone',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        let that = this
        console.log('添加商品数量', res)
      }
    })
    // 商品总数量-1
    if (count > 1) {
      that.data.carts[index].goods_num--
    }
    // 将数值与状态写回
    that.setData({
      carts: that.data.carts
    })
    console.log('carts-:', that.data.carts)
    that.priceCount()
  },
  /* 加数 */
  addCount: function(e) {
    let that = this
    let index = e.target.dataset.index
    let count = that.data.carts[index].goods_num
    let cart_id = that.data.carts[index].id
    wx.request({
      url:
        app.urlData.getURL +
        '/index.php/api/SApi/index/key/' +
        app.urlData.key +
        '/m/updateCartCount/wid/' +
        app.urlData.wid +
        '/sign/' +
        wx.getStorageSync('sign') +
        '/cart_id/' +
        cart_id +
        '/op/' +
        'addone',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        let that = this
        console.log('添加商品数量', res)
      }
    })
    // 商品总数量+1
    that.data.carts[index].goods_num++
    // 将数值与状态写回
    that.setData({
      carts: that.data.carts
    })
    console.log('carts+:', that.data.carts)
    that.priceCount()
  },
  // 计算总价，上面有一个地方冗余了
  priceCount: function(e) {
    let that = this
    that.data.totalMoney = 0
    for (var i = 0; i < that.data.carts.length; i++) {
      if (that.data.carts[i].selected == 1) {
        if (wx.getStorageSync('is_vip') == 1) {
          that.data.totalMoney =
            that.data.totalMoney +
            that.data.carts[i].price_discounts * that.data.carts[i].goods_num
        } else {
          that.data.totalMoney =
            that.data.totalMoney +
            that.data.carts[i].price * that.data.carts[i].goods_num
        }
      }
    }
    that.setData({
      totalMoney: that.data.totalMoney
    })
  },
  // getUserInfo4(e) {
  //   let that = this
  //   if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
  //     wx.showToast({
  //       title: '请先授权才能参与购买结算哦！',
  //       icon: 'none',
  //       duration: 3000
  //     })
  //   } else if (e.detail.errMsg == 'getUserInfo:ok') {
  //     app.getUserInfo(
  //       wx.getStorageSync('sign'),
  //       e.detail.userInfo.nickName,
  //       e.detail.userInfo.avatarUrl,
  //       e.detail.userInfo.gender,
  //       e.detail.encryptedData,
  //       e.detail.iv
  //     ,function(res){
  //       if (res.user_info.customerid == 0){
  //         console.log("测试一下咯")
  //         wx.navigateTo({
  //           url: '/pages/phoneBinding/phoneBinding',
  //         })
  //       }
  //     })
  //     that.toBuy(e)
  //   }
  // },
  getUserInfo4(e){
    let that= this
    if (wx.getStorageSync('customerid') == '' || wx.getStorageSync('customerid') ==0){
      wx.showModal({
        title: '提示',
        content: '您还没有注册，是否去注册',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/phoneBinding/phoneBinding',
            })
          }
        }
      })
    }else{
      that.toBuy(e)
    }
  },
  /* 删除商品 */
  delGoods: function(e) {
    let that = this
    let index = e.target.dataset.index
    let cart_id = that.data.carts[index].id
    let carts = that.data.carts
    // 更新data数据对象
    wx.showModal({
      title: '',
      content: '确定将这个宝贝删除？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url:
              app.urlData.getURL +
              '/index.php/api/SApi/index/key/' +
              app.urlData.key +
              '/m/deleteCart/wid/' +
              app.urlData.wid +
              '/sign/' +
              wx.getStorageSync('sign') +
              '/cart_ids/' +
              cart_id,
            data: {},
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: res => {
              console.log('删除购物车', res)
              if (res.data.status == 1) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'success',
                  duration: 2000
                })
                carts.splice(index, 1)
                that.setData({
                  carts: carts
                })
                that.priceCount()
                console.log('删除成功后数组改变', that.data.carts)
                if (that.data.carts == '') {
                  that.setData({
                    iscart: true,
                    hidden: false
                  })
                }
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '您的好友' + wx.getStorageSync('userName') + '邀请您一起体验！',
      path:
        '/pages/shopCart/shopCart?order_share_id=' + wx.getStorageSync('ydn_id')
    }
  }
})
